package com.api.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.api.model.dto.TranslateResult;
import com.api.apicommon.response.BaseResponse;
import com.api.apicommon.response.ErrorCode;
import com.api.apicommon.response.ResultUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/translation")
public class BaiDuTransController {
    @Value("${api.baidu.app-id}")
    private String appId ;
    @Value("${api.baidu.app-secret}")
    private String appSecret ;
    @Value("${api.baidu.url}")
    private String url;

    /**
     * 百度翻译接口
     *
     * @return
     */
    @GetMapping
    public BaseResponse translation(String query, String from, String to) {
        HashMap<String, Object> params = new HashMap<>();
        buildParam(query, from, to, params);
        HttpResponse response;
        try {
            response = HttpRequest.get(url).form(params).charset("UTF-8")
                    .timeout(60 * 1000).execute();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getLocalizedMessage());
        }

        if (response.getStatus() == HttpStatus.HTTP_OK) {
            String body = response.body();
            TranslateResult translateResult = JSONUtil.toBean(body, TranslateResult.class);
            return ResultUtils.success(translateResult);
        } else {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "翻译失败");
        }
    }

    private void buildParam(String query, String from, String to, HashMap<String, Object> params) {
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appId);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appId + query + salt + appSecret; // 加密前的原文
        params.put("sign", SecureUtil.md5(src));
    }

}
